// 获取搜索输入框
const searchInput = document.getElementById('searchInput');

document.querySelector('.voice-btn').addEventListener('click', () => {
  alert("请说话");

  // 兼容 Edge 和 Chrome 的 Web Speech API
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;

  if (!SpeechRecognition) {
      alert("你的浏览器不支持语音识别，请使用最新版 Edge 或 Chrome！");
      return;
  }

  const recognition = new SpeechRecognition();
  recognition.lang = 'zh-CN';  // 设定语言为中文
  recognition.continuous = true;  // 允许连续识别
  recognition.interimResults = true;  // 允许返回中间结果，防止过早结束

  recognition.start(); // 开始识别
  console.log("语音识别已启动...");

  recognition.onresult = function (event) {
      let transcript = "";
      for (let i = 0; i < event.results.length; i++) {
          transcript += event.results[i][0].transcript;
      }
      console.log("识别结果:", transcript);
      document.getElementById('searchInput').value = transcript; // 填充到搜索框
  };

  recognition.onerror = function (event) {
      console.error("语音识别错误:", event.error);
      alert(`语音识别失败: ${event.error}`);
  };

  recognition.onend = function () {
      console.log("语音识别结束，尝试重启...");
      recognition.start(); // **解决 Edge 识别时间短的问题**
  };
});




document.querySelector('.camera-btn').addEventListener('click', () => {
    console.log('拍照搜索触发');

    // 创建一个隐藏的文件选择框
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';  // 只允许选择图片
    fileInput.style.display = 'none';

    // 监听文件选择
    fileInput.addEventListener('change', () => {
        if (fileInput.files.length > 0) {
            const file = fileInput.files[0];
            console.log("已选择图片:", file.name);

            // 上传图片到后端
            uploadImage(file);
        }
    });

    // 触发文件选择框
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
});

function uploadImage(file) {
    const formData = new FormData();
    formData.append('image', file);

    fetch('/upload_image', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log("后端返回:", data);
        document.getElementById('searchInput').value = data.result;  // 填充搜索框
    })
    .catch(error => {
        console.error("上传失败:", error);
        alert("图片上传失败，请重试！");
    });
}

// 监听搜索按钮点击事件
document.querySelector('.search-btn').addEventListener('click', function () {
  performSearch();
});

// 监听回车键触发搜索
document.getElementById('searchInput').addEventListener('keypress', function (e) {
  if (e.key === 'Enter') {
      performSearch();
  }
});

function performSearch() {
  const searchInput = document.getElementById('searchInput');
  const keyword = searchInput.value.trim();

  if (!keyword) {
      alert("请输入搜索关键词！");
      return;
  }

  console.log('执行搜索:', keyword);

  // 发送请求到 Flask 后端
  fetch('/generate-chart', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query: keyword })
  })
  .then(response => response.json())
  .then(data => {
      if (data.status === "success") {
          console.log('图表数据已更新');
          // 触发图表数据更新
          initLifeExpectancyChart();
      } else {
          alert("图表生成失败，请稍后重试！");
      }
  })
  .catch(error => {
      console.error("请求失败:", error);
      alert("网络错误，请稍后重试！");
  });
}

// 初始化人均寿命与GDP关系演变图表
function initLifeExpectancyChart() {
  const chartDom = document.getElementById('life-chart');
  const myChart = echarts.init(chartDom);
  
  myChart.showLoading();
  
  // 设置根路径
  const ROOT_PATH = '';
  
  fetch('static/json/life-expectancy.json')
    .then(response => response.json())
    .then(data => {
      myChart.hideLoading();
      
      const itemStyle = {
        opacity: 0.8
      };
      
      const sizeFunction = function (x) {
        const y = Math.sqrt(x / 5e8) + 0.1;
        return y * 80;
      };
      
      // Schema:
      const schema = [
        { name: 'Income', index: 0, text: '人均二手经济消费量', unit: '美元' },
        { name: 'LifeExpectancy', index: 1, text: '人均寿命', unit: '岁' },
        { name: 'Population', index: 2, text: '总人口', unit: '' },
        { name: 'Country', index: 3, text: '国家', unit: '' }
      ];
      
      const option = {
        baseOption: {
          timeline: {
            axisType: 'category',
            orient: 'vertical',
            autoPlay: true,
            inverse: true,
            playInterval: 1000,
            left: null,
            right: 0,
            top: 20,
            bottom: 20,
            width: 55,
            height: null,
            symbol: 'none',
            checkpointStyle: {
              borderWidth: 2
            },
            controlStyle: {
              showNextBtn: false,
              showPrevBtn: false
            },
            data: []
          },
          title: [
            {
              text: data.timeline[0],
              textAlign: 'center',
              left: '63%',
              top: '55%',
              textStyle: {
                fontSize: 100,
                color: 'rgba(74,144,226,0.2)'
              }
            },
            {
              text: '各国人均寿命与二手经济关系演变',
              left: 'center',
              top: 10,
              textStyle: {
                fontWeight: 'normal',
                fontSize: 20,
                color: '#4a90e2'
              }
            }
          ],
          tooltip: {
            padding: 5,
            borderWidth: 1,
            formatter: function (obj) {
              const value = obj.value;
              // prettier-ignore
              return schema[3].text + '：' + value[3] + '<br>'
                            + schema[1].text + '：' + value[1] + schema[1].unit + '<br>'
                            + schema[0].text + '：' + value[0] + schema[0].unit + '<br>'
                            + schema[2].text + '：' + value[2] + '<br>';
            }
          },
          grid: {
            top: 100,
            containLabel: true,
            left: 30,
            right: '110'
          },
          xAxis: {
            type: 'log',
            name: '人均二手经济消费量',
            max: 50000,
            min: 300,
            nameGap: 25,
            nameLocation: 'middle',
            nameTextStyle: {
              fontSize: 18,
              color: '#4a90e2'
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              formatter: '{value} $',
              color: '#666'
            }
          },
          yAxis: {
            type: 'value',
            name: '平均寿命',
            max: 100,
            nameTextStyle: {
              fontSize: 18,
              color: '#4a90e2'
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              formatter: '{value} ',
              color: '#666'
            }
          },
          visualMap: [
            {
              show: false,
              dimension: 3,
              categories: data.counties,
              inRange: {
                color: (function () {
                  // prettier-ignore
                  const colors = ['#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba'];
                  return colors.concat(colors);
                })()
              }
            }
          ],
          series: [
            {
              type: 'scatter',
              itemStyle: itemStyle,
              data: data.series[0],
              symbolSize: function (val) {
                return sizeFunction(val[2]);
              }
            }
          ],
          animationDurationUpdate: 1000,
          animationEasingUpdate: 'quinticInOut'
        },
        options: []
      };
      
      for (let n = 0; n < data.timeline.length; n++) {
        option.baseOption.timeline.data.push(data.timeline[n]);
        option.options.push({
          title: {
            show: true,
            text: data.timeline[n] + ''
          },
          series: {
            name: data.timeline[n],
            type: 'scatter',
            itemStyle: itemStyle,
            data: data.series[n],
            symbolSize: function (val) {
              return sizeFunction(val[2]);
            }
          }
        });
      }
      
      myChart.setOption(option);
    })
    .catch(error => {
      console.error("加载数据失败:", error);
      myChart.hideLoading();
      alert("数据加载失败，请稍后重试！");
    });
}

// 页面加载完成后初始化图表
document.addEventListener('DOMContentLoaded', function() {
  initLifeExpectancyChart();
});

// app.js
document.addEventListener('DOMContentLoaded', function() {
    // 数据配置
    const schema = [
        { name: '汽车', index: 1, text: '汽车' },
        { name: '文玩', index: 2, text: '文玩' },
        { name: '手机', index: 3, text: '手机' },
        { name: '个护', index: 4, text: '个护' },
        { name: '电脑', index: 5, text: '电脑' },
        { name: '生活用品', index: 6, text: '生活用品' },
        { name: '等级', index: 7, text: '等级' }
    ];

    const rawData = [
        // 北京数据
        [55, 9, 56, 0.46, 18, 6, '5', '北京'],
        [25, 11, 21, 0.65, 34, 9, '6', '北京'],
        [56, 7, 63, 0.3, 14, 5, '5', '北京'],
        [33, 7, 29, 0.33, 16, 6, '6', '北京'],
        [42, 24, 44, 0.76, 40, 16, '6', '北京'],
        [82, 58, 90, 1.77, 68, 33, '5', '北京'],
        [74, 49, 77, 1.46, 48, 27, '5', '北京'],
        [78, 55, 80, 1.29, 59, 29, '5', '北京'],
        [267, 216, 280, 4.8, 108, 64, '2', '北京'],
        [185, 127, 216, 2.52, 61, 27, '3', '北京'],
        [39, 19, 38, 0.57, 31, 15, '6', '北京'],
        [41, 11, 40, 0.43, 21, 7, '6', '北京'],
        [64, 38, 74, 1.04, 46, 22, '5', '北京'],
        [108, 79, 120, 1.7, 75, 41, '4', '北京'],
        [108, 63, 116, 1.48, 44, 26, '4', '北京'],
        [33, 6, 29, 0.34, 13, 5, '6', '北京'],
        [94, 66, 110, 1.54, 62, 31, '5', '北京'],
        [186, 142, 192, 3.88, 93, 79, '3', '北京'],
        [57, 31, 54, 0.96, 32, 14, '5', '北京'],
        [22, 8, 17, 0.48, 23, 10, '6', '北京'],
        [39, 15, 36, 0.61, 29, 13, '6', '北京'],
        [94, 69, 114, 2.08, 73, 39, '5', '北京'],
        [99, 73, 110, 2.43, 76, 48, '5', '北京'],
        [31, 12, 30, 0.5, 32, 16, '6', '北京'],
        [42, 27, 43, 1, 53, 22, '6', '北京'],
        [154, 117, 157, 3.05, 92, 58, '3', '北京'],
        [234, 185, 230, 4.09, 123, 69, '2', '北京'],
        [160, 120, 186, 2.77, 91, 50, '3', '北京'],
        [134, 96, 165, 2.76, 83, 41, '4', '北京'],
        [52, 24, 60, 1.03, 50, 21, '5', '北京'],
        [46, 5, 49, 0.28, 10, 6, '6', '北京'],
    
        // 广州数据
        [26, 37, 27, 1.163, 27, 13, '6', '广州'],
        [85, 62, 71, 1.195, 60, 8, '5', '广州'],
        [78, 38, 74, 1.363, 37, 7, '5', '广州'],
        [21, 21, 36, 0.634, 40, 9, '6', '广州'],
        [41, 42, 46, 0.915, 81, 13, '6', '广州'],
        [56, 52, 69, 1.067, 92, 16, '5', '广州'],
        [64, 30, 28, 0.924, 51, 2, '5', '广州'],
        [55, 48, 74, 1.236, 75, 26, '5', '广州'],
        [76, 85, 113, 1.237, 114, 27, '5', '广州'],
        [91, 81, 104, 1.041, 56, 40, '5', '广州'],
        [84, 39, 60, 0.964, 25, 11, '5', '广州'],
        [64, 51, 101, 0.862, 58, 23, '5', '广州'],
        [70, 69, 120, 1.198, 65, 36, '5', '广州'],
        [77, 105, 178, 2.549, 64, 16, '5', '广州'],
        [109, 68, 87, 0.996, 74, 29, '4', '广州'],
        [73, 68, 97, 0.905, 51, 34, '5', '广州'],
        [54, 27, 47, 0.592, 53, 12, '5', '广州'],
        [51, 61, 97, 0.811, 65, 19, '5', '广州'],
        [91, 71, 121, 1.374, 43, 18, '5', '广州'],
        [73, 102, 182, 2.787, 44, 19, '5', '广州'],
        [73, 50, 76, 0.717, 31, 20, '5', '广州'],
        [84, 94, 140, 2.238, 68, 18, '5', '广州'],
        [93, 77, 104, 1.165, 53, 7, '5', '广州'],
        [99, 130, 227, 3.97, 55, 15, '5', '广州'],
        [146, 84, 139, 1.094, 40, 17, '4', '广州'],
        [113, 108, 137, 1.481, 48, 15, '4', '广州'],
        [81, 48, 62, 1.619, 26, 3, '5', '广州'],
        [56, 48, 68, 1.336, 37, 9, '5', '广州'],
        [82, 92, 174, 3.29, 0, 13, '5', '广州'],
        [106, 116, 188, 3.628, 101, 16, '4', '广州'],
        [118, 50, 0, 1.383, 76, 11, '4', '广州'],
    
        // 上海数据
        [91, 45, 125, 0.82, 34, 23, '5', '上海'],
        [65, 27, 78, 0.86, 45, 29, '5', '上海'],
        [83, 60, 84, 1.09, 73, 27, '5', '上海'],
        [109, 81, 121, 1.28, 68, 51, '4', '上海'],
        [106, 77, 114, 1.07, 55, 51, '4', '上海'],
        [109, 81, 121, 1.28, 68, 51, '4', '上海'],
        [106, 77, 114, 1.07, 55, 51, '4', '上海'],
        [89, 65, 78, 0.86, 51, 26, '5', '上海'],
        [53, 33, 47, 0.64, 50, 17, '5', '上海'],
        [80, 55, 80, 1.01, 75, 24, '5', '上海'],
        [117, 81, 124, 1.03, 45, 24, '4', '上海'],
        [99, 71, 142, 1.1, 62, 42, '5', '上海'],
        [95, 69, 130, 1.28, 74, 50, '5', '上海'],
        [116, 87, 131, 1.47, 84, 40, '4', '上海'],
        [108, 80, 121, 1.3, 85, 37, '4', '上海'],
        [134, 83, 167, 1.16, 57, 43, '4', '上海'],
        [79, 43, 107, 1.05, 59, 37, '5', '上海'],
        [71, 46, 89, 0.86, 64, 25, '5', '上海'],
        [97, 71, 113, 1.17, 88, 31, '5', '上海'],
        [84, 57, 91, 0.85, 55, 31, '5', '上海'],
        [87, 63, 101, 0.9, 56, 41, '5', '上海'],
        [104, 77, 119, 1.09, 73, 48, '4', '上海'],
        [87, 62, 100, 1, 72, 28, '5', '上海'],
        [168, 128, 172, 1.49, 97, 56, '3', '上海'],
        [65, 45, 51, 0.74, 39, 17, '5', '上海'],
        [39, 24, 38, 0.61, 47, 17, '6', '上海'],
        [39, 24, 39, 0.59, 50, 19, '6', '上海'],
        [93, 68, 96, 1.05, 79, 29, '5', '上海'],
        [188, 143, 197, 1.66, 99, 51, '3', '上海'],
        [174, 131, 174, 1.55, 108, 50, '3', '上海'],
        [187, 143, 201, 1.39, 89, 53, '3', '上海']
    ];
    // 常量定义
    const CATEGORY_DIM_COUNT = 6;
    const GAP = 2;
    const BASE_LEFT = 5;
    const BASE_TOP = 10;
    const GRID_WIDTH = (100 - BASE_LEFT - GAP) / CATEGORY_DIM_COUNT - GAP;
    const GRID_HEIGHT = (100 - BASE_TOP - GAP) / CATEGORY_DIM_COUNT - GAP;
    const CATEGORY_DIM = 7;
    const SYMBOL_SIZE = 4;

    // 工具函数
    function retrieveScatterData(data, dimX, dimY) {
        let result = [];
        for (let i = 0; i < data.length; i++) {
          let item = [data[i][dimX], data[i][dimY]];
          item[CATEGORY_DIM] = data[i][CATEGORY_DIM];
          result.push(item);
        }
        return result;
      }

      function generateGrids() {
        let index = 0;
        const grid = [];
        const xAxis = [];
        const yAxis = [];
        const series = [];
        for (let i = 0; i < CATEGORY_DIM_COUNT; i++) {
          for (let j = 0; j < CATEGORY_DIM_COUNT; j++) {
            if (CATEGORY_DIM_COUNT - i + j >= CATEGORY_DIM_COUNT) {
              continue;
            }
            grid.push({
              left: BASE_LEFT + i * (GRID_WIDTH + GAP) + '%',
              top: BASE_TOP + j * (GRID_HEIGHT + GAP) + '%',
              width: GRID_WIDTH + '%',
              height: GRID_HEIGHT + '%'
            });
            xAxis.push({
              splitNumber: 3,
              position: 'top',
              axisLine: {
                show: j === 0,
                onZero: false
              },
              axisTick: {
                show: j === 0,
                inside: true
              },
              axisLabel: {
                show: j === 0
              },
              type: 'value',
              gridIndex: index,
              scale: true
            });
            yAxis.push({
              splitNumber: 3,
              position: 'right',
              axisLine: {
                show: i === CATEGORY_DIM_COUNT - 1,
                onZero: false
              },
              axisTick: {
                show: i === CATEGORY_DIM_COUNT - 1,
                inside: true
              },
              axisLabel: {
                show: i === CATEGORY_DIM_COUNT - 1
              },
              type: 'value',
              gridIndex: index,
              scale: true
            });
            series.push({
              type: 'scatter',
              symbolSize: SYMBOL_SIZE,
              xAxisIndex: index,
              yAxisIndex: index,
              data: retrieveScatterData(rawData, i, j)
            });
            index++;
          }
        }
        return {
          grid,
          xAxis,
          yAxis,
          series
        };
      }

    // 初始化图表
    const myChart = echarts.init(document.getElementById('threechart'));
    const gridOption = generateGrids();

    // 完整配置项
    const option = {
        title: {
            text: '重要城市二手商品购买多维度分析',
            left: 'center',
            textStyle: {
                fontSize: 18,
                color: '#333'
            }
        },
        animation: false,
        brush: {
            brushLink: 'all',
            xAxisIndex: gridOption.xAxis.map((_, idx) => idx),
            yAxisIndex: gridOption.yAxis.map((_, idx) => idx),
            inBrush: { opacity: 1 }
        },
        visualMap: {
            type: 'piecewise',
            categories: ['北京', '上海', '广州'],
            dimension: CATEGORY_DIM,
            orient: 'horizontal',
            top: 30,
            left: 'center',
            inRange: { color: ['#51689b', '#ce5c5c', '#fbc357'] },
            outOfRange: { color: '#ddd' },
            seriesIndex: gridOption.series.map((_, idx) => idx)
        },
        tooltip: {
            trigger: 'item',
            formatter: params => `
                <strong>${params.data.city}</strong><br/>
                ${schema[params.seriesIndex % 6].text}: ${params.value[0]}<br/>
                ${schema[Math.floor(params.seriesIndex / 6)].text}: ${params.value[1]}
            `
        },
        parallelAxis: [
            { dim: 0, name: schema[0].text },
            { dim: 1, name: schema[1].text },
            { dim: 2, name: schema[2].text },
            { dim: 3, name: schema[3].text },
            { dim: 4, name: schema[4].text },
            { dim: 5, name: schema[5].text },
            {
              dim: 6,
              name: schema[6].text,
              type: 'category',
              data: ['6', '5', '4', '3', '2', '1']
            }
          ],
          parallel: {
            bottom: '5%',
            left: '2%',
            height: '30%',
            width: '55%',
            parallelAxisDefault: {
              type: 'value',
              name: '购买得分',
              nameLocation: 'end',
              nameGap: 20,
              splitNumber: 3,
              nameTextStyle: {
                fontSize: 14
              },
              axisLine: {
                lineStyle: {
                  color: '#555'
                }
              },
              axisTick: {
                lineStyle: {
                  color: '#555'
                }
              },
              splitLine: {
                show: false
              },
              axisLabel: {
                color: '#555'
              }
            }
          },
        xAxis: gridOption.xAxis,
        yAxis: gridOption.yAxis,
        grid: gridOption.grid,
        series: [
            {
                name: 'parallel',
                type: 'parallel',
                smooth: true,
                lineStyle: { width: 1, opacity: 0.3 },
                data: rawData,
                itemStyle: { borderWidth: 0.5 }
            },
            ...gridOption.series
        ]
    };

    myChart.setOption(option);

    // 窗口自适应
    window.addEventListener('resize', () => myChart.resize());

    // 添加交互事件
    myChart.on('brushSelected', params => {
        console.log('当前选中的数据索引:', params.batch[0].selected[0].dataIndex);
    });
});